package com.pwser.zk;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.ZooDefs.Ids;

public class DistributedServer {
	
	private static final String connectString = "192.168.33.102:2181,192.168.33.103:2181,192.168.33.104:2181";
	private static final int sessionTimeout = 2000;
	private static final String serversPath = "/servers";
	private ZooKeeper zkClient = null;
	
	/**
	 * 创建zk连接
	 * @throws Exception 
	 */
	public void getConnect() throws Exception {
		zkClient = new ZooKeeper(connectString, sessionTimeout, null);
	}
	
	/**
	 * 注册服务器信息
	 * @throws Exception 
	 */
	public void registerServer(String hostname) throws Exception  {
		String serverNode = zkClient.create(serversPath + "/" + hostname, hostname.getBytes("UTF-8"), Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
		System.out.println(hostname + " is online..." + " This serversPath is " + serverNode);
	}
	
	/**
	 * 服务端业务操作
	 * @throws Exception 
	 */
	public void handleBussiness(String hostname) throws Exception  {
		System.out.println(hostname + " start working...");
		Thread.sleep(Long.MAX_VALUE);
	}
	
	public static void main(String[] args) throws Exception {
		DistributedServer server = new DistributedServer();
		//创建zk连接
		server.getConnect();
		//根据参数注册服务
		server.registerServer(args[0]);
		//服务端业务操作
		server.handleBussiness(args[0]);
	}

}
